package xyy.d3erpapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import xyy.d3erpapi.pojo.poppo.*;
import xyy.d3erpapi.service.PopApiService;
import xyy.d3erpapi.utils.IpUtils;
import xyy.d3erpapi.utils.MD5Util;
import xyy.d3erpapi.utils.http.RedirectUtil;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PopApiServiceImpl implements PopApiService {

    @Value("${pop.api.host}")
    private String popHost;
    @Resource
    private Environment env;


    /**
     * 数据上报接口
     *
     * @param
     * @return
     */
    @Override
    public <T> ApiRPCResult<Boolean> pushDataInfo(List<T> lsit, Integer taskId) {
        Map<String, Object> map = buildPopTaskQueryParam(taskId, lsit);
//        log.info("数据上报,JsonData: {}", JSON.toJSONString(map));
        String body = RedirectUtil.doPostByJson(popHost + env.getProperty("pop.api.url.push"), JSON.toJSONString(map));
        ApiRPCResult<Boolean> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#数据上报失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(map), JSON.toJSONString(apiRPCResult));
            return new ApiRPCResult<>();
        }
        log.info("数据上报成功,JsonData: {}", JSON.toJSONString(apiRPCResult));
        return apiRPCResult;
    }

    @Override
    public <T> List<T> pullDataInfo(Integer taskId, Class<T> tClass) {
        Map<String, Object> map = buildPopTaskQueryParam(taskId, null);
        String body = RedirectUtil.doGetParam(popHost + env.getProperty("pop.api.url.pull"), map);
        ApiRPCResult<ResultDto> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#平台数据下推失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(map), JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }
        if (apiRPCResult.getData() == null) {
            log.warn("#平台暂无可拉取数据 apiRPCResult：{}", JSON.toJSONString(apiRPCResult));
            return new ArrayList<>();
        }

        ResultDto resultData = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        String dataJson = resultData.getDataJson();
        log.info("拉取到的平台数据: {}", dataJson);
        List<T> ts = JSON.parseArray(dataJson, tClass);
        return ts;
    }

    /**
     * 数据拉取接口
     *
     * @param taskId
     * @return
     */


    /**
     * 数据筛选接口
     *
     * @param taskId
     * @return
     */
    @Override
    public List<String> queryData(Integer taskId) {
        //查询出需要上传库存的品
        Map<String, Object> objectMap = buildPopTaskQueryParam(taskId, null);
        String body = RedirectUtil.doGetParam("https://h-api.ybm100.com/api/hackTask/queryTaskCondition", objectMap);
        ApiRPCResult apiRpcResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRpcResult.getData() == null) {
            log.warn("#平台暂时无可用数据 apiRPCResult：{}", JSON.toJSONString(apiRpcResult));
            return new ArrayList<>();
        }
        ResultDto resultData = JSON.parseObject(JSON.toJSONString(apiRpcResult.getData()), ResultDto.class);
        String dataJson = resultData.getDataJson();
        QueryTaskData queryTaskData = JSON.parseObject(dataJson, QueryTaskData.class);
        return queryTaskData.getListQueryParam();
    }

    @Override
    public ApiRPCResult<Boolean> orderCallBack(List<SellerOrderCallBackDto> callBackDtoList) {
        Map<String, Object> map = buildPopTaskQueryParam(10086, callBackDtoList);
        String body = RedirectUtil.doPostByJson(popHost + env.getProperty("pop.api.url.orderCallback"), JSON.toJSONString(map));
        ApiRPCResult<Boolean> apiRpcResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRpcResult.getData() == null) {
            log.warn("#订单回调失败 apiRPCResult：{}", JSON.toJSONString(apiRpcResult));
            return new ApiRPCResult<>();
        }
        return apiRpcResult;
    }

    @Override
    public ApiRPCResult<Boolean> customerCallBack(List<SellerCustomerCallBackDto> callBackDtoList) {
        Map<String, Object> map = buildPopTaskQueryParam(10086, callBackDtoList);
        String body = RedirectUtil.doPostByJson(popHost + env.getProperty("pop.api.url.clientCallBack"), JSON.toJSONString(map));
        ApiRPCResult<Boolean> apiRpcResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRpcResult.getData() == null) {
            log.warn("#客户回调失败 apiRPCResult：{}", JSON.toJSONString(apiRpcResult));
            return new ApiRPCResult<>();
        }
        return apiRpcResult;
    }

    @Override
    public void pushClientInfo() {
        Map<String, Object> objectMap = buildPopTaskQueryParam(00000, null);
        Map<String, String> mapNew = new HashMap<>();
        for (Map.Entry<String, Object> map : objectMap.entrySet()) {
            mapNew.put(map.getKey(), map.getValue().toString());
        }
        log.info("集合 : {}", JSON.toJSONString(objectMap));
        String body = RedirectUtil.doPostByFrom(popHost + env.getProperty("pop.api.url.beat"), mapNew);
        ApiRPCResult apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#心跳失败  apiRPCResult: {}", JSON.toJSONString(apiRPCResult));
            return;
        }
        log.info("心跳成功!!!!!");
    }

    private <T> Map<String, Object> buildPopTaskQueryParam(Integer taskId, List<T> list) {


        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(env.getProperty("pop.orgId"));
        taskQueryParam.setAppId(env.getProperty("pop.appId"));
        if (taskId != null && taskId != 00000) {
            taskQueryParam.setTaskId(taskId);
        }
        if (taskId == 00000) {
            String ipAddress = "";
            InetAddress address = IpUtils.getLocalHostLANAddress();
            if (address != null) {
                ipAddress = address.getHostAddress();
            }
            taskQueryParam.setVersion("3.5");
            taskQueryParam.setJsonData(ipAddress);
        }
        if (!CollectionUtils.isEmpty(list)) {
            taskQueryParam.setJsonData(JSON.toJSONString(list));
        }
        Map<String, Object> popParamMap = JSON.parseObject(JSON.toJSONString(taskQueryParam)).getInnerMap();
        taskQueryParam.setSign(MD5Util.encrypt(popParamMap, env.getProperty("pop.appSecret")));
        Map<String, Object> popParamMapNew = JSON.parseObject(JSON.toJSONString(taskQueryParam)).getInnerMap();
        return popParamMapNew;
    }
    @Override
    public ApiRPCResult<Boolean> pushDataInfo(Map<String, Object> var1) {
        String body = RedirectUtil.doPostByJson("https://h-api.ybm100.com/api/hackTask/pushDataInfo", JSON.toJSONString(var1));
        ApiRPCResult<Boolean> apiRPCResult = JSON.parseObject(body, ApiRPCResult.class);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#数据上报失败 taskQueryParam:{}, apiRPCResult：{}", JSONObject.toJSONString(var1), JSON.toJSONString(apiRPCResult));
            return new ApiRPCResult<>();
        }
        log.info("数据上报成功,JsonData: {}", JSON.toJSONString(var1));
        log.info("接口信息: {}", JSON.toJSONString(apiRPCResult));
        return apiRPCResult;
    }
}
